package gk.example.receiver;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import cn.bmob.push.PushConstants;
import cn.bmob.v3.BmobUser;

import com.example.gkdate.R;

public class PushMessageReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(PushConstants.ACTION_MESSAGE)) {
			ActivityManager activityManager = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			String runningActivity = activityManager.getRunningTasks(1).get(0).topActivity
					.getClassName();
			try {
				JSONObject jObject = new JSONObject(
						intent.getStringExtra(PushConstants.EXTRA_PUSH_MESSAGE_STRING));
				String msg = jObject.getString("Msg");
				String activity = jObject.getString("Activity");
				String name = jObject.getString("SenderName");
				String dataid=jObject.getString("DateId");
				if (activity.equals("ChatActivity")
						&& runningActivity
								.equals("gk.example.activity.ChatActivity")) {
					Intent Msgintent = new Intent();
					Bundle bundle = new Bundle();
					bundle.putString("Msg", msg);
					bundle.putString("SenderName", name);
					bundle.putString("DateId", dataid);
					Msgintent.putExtras(bundle);
					Msgintent.setAction("android.intent.action.MsgReceiver");
					context.sendBroadcast(Msgintent);
				} else if (activity.equals("ChatActivity")
						&& BmobUser.getCurrentUser(context) != null
						&& !runningActivity
								.equals("gk.example.activity.ChatActivity")) {
					showNotification(name + ":" + msg,
							context, dataid);

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	private void showNotification(String content, Context context, String dataid) {

		NotificationCompat.Builder builder = new NotificationCompat.Builder(
				context);
		NotificationManager manager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Intent intent = new Intent();
		builder.setSmallIcon(R.drawable.ic_launcher);
		intent.putExtra("DataId", dataid);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				intent, PendingIntent.FLAG_ONE_SHOT);
		builder.setContentTitle("约会消息");
		builder.setContentText(content);
		builder.setAutoCancel(true);
		builder.setDefaults(Notification.DEFAULT_ALL);
		builder.setContentIntent(pendingIntent);
		manager.notify(0x00, builder.build());

	}

}
